import json
import re


def convert_to_seconds(time_str):
    """将x时x分x秒格式的时间字符串转换为秒数"""
    # 去除表情符号等非数字字符
    time_str = ''.join(filter(str.isdigit, time_str))
    hours = 0
    minutes = 0
    seconds = 0
    if '时' in time_str:
        parts = time_str.split('时')
        hours = int(parts[0])
        time_str = parts[1]
    if '分' in time_str:
        parts = time_str.split('分')
        minutes = int(parts[0])
        seconds = int(parts[1]) if parts[1] else 0
    else:
        seconds = int(time_str)

    return hours * 3600 + minutes * 60 + seconds


def process_file(file_path):
    result = []
    pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (开始哭闹|停止哭闹).*?((?:\d+时)?(?:\d+分)?\d+秒)'
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            line = line.strip()
            if not line:
                continue
            match = re.search(pattern, line)
            if match:
                date = match.group(1)
                state = match.group(2)
                duration_str = match.group(3)
                duration = convert_to_seconds(duration_str)
                item = {
                    "date": date,
                    "state": state,
                    "duration": duration
                }
                result.append(item)
            else:
                print(f"跳过格式不正确的行: {line}")
    return result


if __name__ == "__main__":
    file_path = 'prediction.txt'
    data = process_file(file_path)
    with open('output.json', 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)
